<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>证书查询</span>
        <el-button style="float: right; padding: 3px 0" link @click="goBack">返回列表</el-button>
      </div>

      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
        <el-form-item label="证书编号" prop="certificateNo">
          <el-input
            v-model="queryParams.certificateNo"
            placeholder="请输入证书编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="产品" prop="productId">
          <el-select v-model="queryParams.productId" placeholder="请选择产品" clearable>
            <el-option
              v-for="item in productOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="批次号" prop="batchNo">
          <el-input
            v-model="queryParams.batchNo"
            placeholder="请输入批次号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="certificateStatus">
          <el-select v-model="queryParams.certificateStatus" placeholder="请选择状态" clearable>
            <el-option label="已签发" value="已签发" />
            <el-option label="已作废" value="已作废" />
            <el-option label="草稿" value="草稿" />
          </el-select>
        </el-form-item>
        <el-form-item label="签发日期" prop="issueDateRange">
          <el-date-picker
            v-model="dateRange"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['certificate:manage:export']"
          >导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-check"
            size="mini"
            @click="handleVerify"
          >证书验证</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="certificateList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="证书编号" align="center" prop="certificateNo" />
        <el-table-column label="模板" align="center" prop="templateName" :show-overflow-tooltip="true" />
        <el-table-column label="产品" align="center" prop="productName" :show-overflow-tooltip="true" />
        <el-table-column label="批次" align="center" prop="batchNo" />
        <el-table-column label="签发日期" align="center" prop="issueDate" width="100">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.issueDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="签发人" align="center" prop="issuer" />
        <el-table-column label="状态" align="center" prop="certificateStatus">
          <template slot-scope="scope">
            <el-tag :type="scope.row.certificateStatus === '已签发' ? 'success' : (scope.row.certificateStatus === '已作废' ? 'danger' : 'info')">
              {{ scope.row.certificateStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              link
              icon="el-icon-view"
              @click="handlePreview(scope.row)"
              v-hasPermi="['certificate:manage:query']"
            >预览</el-button>
            <el-button
              size="mini"
              link
              icon="el-icon-printer"
              @click="handlePrint(scope.row)"
              v-hasPermi="['certificate:manage:query']"
            >打印</el-button>
            <el-button
              size="mini"
              link
              icon="el-icon-download"
              @click="handleDownload(scope.row)"
              v-hasPermi="['certificate:manage:export']"
            >下载</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 预览证书对话框 -->
      <el-dialog title="预览证书" :visible.sync="previewOpen" width="800px" append-to-body>
        <div v-html="previewContent" class="certificate-preview"></div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="previewOpen = false">关 闭</el-button>
          <el-button type="primary" @click="printPreview">打 印</el-button>
        </div>
      </el-dialog>

      <!-- 证书验证对话框 -->
      <el-dialog title="证书验证" :visible.sync="verifyDialogVisible" width="500px" append-to-body>
        <el-form ref="verifyForm" :model="verifyForm" label-width="80px">
          <el-form-item label="证书编号" prop="certificateNo" :rules="[{ required: true, message: '请输入证书编号', trigger: 'blur' }]">
            <el-input v-model="verifyForm.certificateNo" placeholder="请输入证书编号"></el-input>
          </el-form-item>
        </el-form>
        
        <div v-if="verifyResult" class="verify-result">
          <el-result
            :icon="verifyResult.valid ? 'success' : 'error'"
            :title="verifyResult.valid ? '证书有效' : '证书无效'"
            :sub-title="verifyResult.message"
          >
            <template v-if="verifyResult.valid" slot="extra">
              <el-button type="primary" size="medium" @click="handlePreviewVerified">查看证书</el-button>
            </template>
          </el-result>
        </div>
        
        <div slot="footer" class="dialog-footer">
          <el-button @click="verifyDialogVisible = false">关 闭</el-button>
          <el-button type="primary" @click="submitVerifyForm" :loading="verifying">验 证</el-button>
        </div>
      </el-dialog>

      <!-- 打印记录对话框 -->
      <el-dialog title="打印记录" :visible.sync="printHistoryDialogVisible" width="700px" append-to-body>
        <el-table :data="printHistory" style="width: 100%">
          <el-table-column prop="printTime" label="打印时间" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.printTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="printBy" label="打印人" width="120"></el-table-column>
          <el-table-column prop="printIp" label="IP地址"></el-table-column>
          <el-table-column prop="printDevice" label="设备信息" :show-overflow-tooltip="true"></el-table-column>
        </el-table>
        <div slot="footer" class="dialog-footer">
          <el-button @click="printHistoryDialogVisible = false">关 闭</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { listCertificate, getCertificate, previewCertificate, printCertificate, exportCertificate, verifyCertificate, getCertificatePrintHistory } from "@/api/certificate/manage";
import { listProduct } from "@/api/qep/product";

export default {
  name: "CertificateQuery",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 证书表格数据
      certificateList: [],
      // 日期范围
      dateRange: [],
      // 产品选项
      productOptions: [],
      // 预览窗口
      previewOpen: false,
      // 预览内容
      previewContent: "",
      // 证书验证对话框
      verifyDialogVisible: false,
      // 验证表单
      verifyForm: {
        certificateNo: ""
      },
      // 验证结果
      verifyResult: null,
      // 验证中
      verifying: false,
      // 已验证的证书ID
      verifiedCertificateId: null,
      // 打印记录对话框
      printHistoryDialogVisible: false,
      // 打印记录
      printHistory: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        certificateNo: null,
        productId: null,
        batchNo: null,
        certificateStatus: null,
        beginIssueDate: null,
        endIssueDate: null
      }
    };
  },
  created() {
    this.getList();
    this.getProductOptions();
  },
  methods: {
    /** 查询证书列表 */
    getList() {
      this.loading = true;
      
      // 处理日期范围
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.beginIssueDate = this.dateRange[0];
        this.queryParams.endIssueDate = this.dateRange[1];
      } else {
        this.queryParams.beginIssueDate = null;
        this.queryParams.endIssueDate = null;
      }
      
      listCertificate(this.queryParams).then(response => {
        this.certificateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取产品选项 */
    getProductOptions() {
      listProduct({ pageSize: 100 }).then(response => {
        this.productOptions = response.rows || [];
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 返回列表 */
    goBack() {
      this.$router.push('/certificate/manage');
    },
    /** 预览按钮操作 */
    handlePreview(row) {
      previewCertificate(row.id).then(response => {
        this.previewContent = response.data;
        this.previewOpen = true;
      });
    },
    /** 打印预览内容 */
    printPreview() {
      const printWindow = window.open('', '_blank');
      printWindow.document.write(`
        <html>
          <head>
            <title>证书打印</title>
            <style>
              body { font-family: Arial, sans-serif; }
              @media print {
                body { margin: 0; padding: 0; }
              }
            </style>
          </head>
          <body>
            ${this.previewContent}
            <script>
              window.onload = function() {
                window.print();
                setTimeout(function() { window.close(); }, 500);
              };
            </script>
          </body>
        </html>
      `);
      printWindow.document.close();
    },
    /** 打印按钮操作 */
    handlePrint(row) {
      printCertificate(row.id).then(response => {
        // 创建打印窗口
        const printContent = response.data;
        const printWindow = window.open('', '_blank');
        printWindow.document.write(`
          <html>
            <head>
              <title>证书打印</title>
              <style>
                body { font-family: Arial, sans-serif; }
                @media print {
                  body { margin: 0; padding: 0; }
                }
              </style>
            </head>
            <body>
              ${printContent}
              <script>
                window.onload = function() {
                  window.print();
                  setTimeout(function() { window.close(); }, 500);
                };
              </script>
            </body>
          </html>
        `);
        printWindow.document.close();
      });
    },
    /** 下载按钮操作 */
    handleDownload(row) {
      this.download('certificate/manage/download/' + row.id, {}, row.certificateNo + '.pdf');
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('certificate/manage/export', {
        ...this.queryParams
      }, `certificate_${new Date().getTime()}.xlsx`)
    },
    /** 证书验证按钮操作 */
    handleVerify() {
      this.verifyForm = {
        certificateNo: ""
      };
      this.verifyResult = null;
      this.verifiedCertificateId = null;
      this.verifyDialogVisible = true;
    },
    /** 提交验证表单 */
    submitVerifyForm() {
      this.$refs.verifyForm.validate(valid => {
        if (valid) {
          this.verifying = true;
          verifyCertificate(this.verifyForm.certificateNo).then(response => {
            this.verifyResult = response.data;
            if (this.verifyResult.valid && this.verifyResult.certificateId) {
              this.verifiedCertificateId = this.verifyResult.certificateId;
            }
            this.verifying = false;
          }).catch(() => {
            this.verifying = false;
          });
        }
      });
    },
    /** 预览已验证证书 */
    handlePreviewVerified() {
      if (this.verifiedCertificateId) {
        previewCertificate(this.verifiedCertificateId).then(response => {
          this.previewContent = response.data;
          this.verifyDialogVisible = false;
          this.previewOpen = true;
        });
      }
    },
    /** 查看打印记录 */
    handlePrintHistory(row) {
      getCertificatePrintHistory(row.id).then(response => {
        this.printHistory = response.data || [];
        this.printHistoryDialogVisible = true;
      });
    }
  }
};
</script>

<style scoped>
.certificate-preview {
  padding: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  min-height: 400px;
  max-height: 600px;
  overflow-y: auto;
}
.verify-result {
  margin-top: 20px;
}
</style> 